﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StockFinder.DataAccess;
using System.Net;
using System.Net.Mail;
using StockFinder.Model;
using StockFinder.Network;

namespace StockFinder.PriceBreakRealtimeConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            var priceBreachContenders = PriceBreachDataAccess.GetAllPriceBreachContenders();

            Console.WriteLine(string.Format("{0} price breach contenders", priceBreachContenders.Count));

            //US market opens @ 2:30pm
            var marketOpenDateTime = DateTime.Today.AddHours(14).AddMinutes(30);
            const int TOTAL_MARKET_MINUTES = 390;

            var timeSinceMarketOpen = DateTime.Now - marketOpenDateTime;

            var minutesSinceMarketOpen = Math.Round(timeSinceMarketOpen.TotalMinutes, 0);

            var percentageTimeSinceMarketOpen = (minutesSinceMarketOpen / TOTAL_MARKET_MINUTES) * 100;

            Console.WriteLine(string.Format("{0}% of market session", percentageTimeSinceMarketOpen));

            if (priceBreachContenders != null)
            {
                var sb = new StringBuilder();

                foreach (var priceBreachContender in priceBreachContenders)
                {
                    Console.WriteLine(string.Format("Getting data for {0}", priceBreachContender.Symbol));

                    //download realtime price
                    using (var wc = new ProxiedWebClient())
                    {
                        string url = string.Format("http://download.finance.yahoo.com/d/quotes.csv?s={0}&f=l1va2&e=.csv", priceBreachContender.Symbol);

                        string realTimeQuoteInfo = null;

                        for (int i = 0; i < 10; i++)
                        {
                            try
                            {
                                realTimeQuoteInfo = wc.DownloadString(url);
                                break;
                            }
                            catch (Exception exception)
                            {
                                Console.WriteLine(string.Format("Exception getting data --> {0}", exception.Message));
                            }
                        }                        
                        
                        realTimeQuoteInfo = realTimeQuoteInfo.Replace(Environment.NewLine, string.Empty);

                        var cells = realTimeQuoteInfo.Split(new[] { ',' });

                        var price = Convert.ToDecimal(cells[0]);
                        var volume = Convert.ToInt64(cells[1]);
                        var averageVolume = Convert.ToInt64(cells[2]);

                        if (price > priceBreachContender.Price)
                        {
                            Console.WriteLine(string.Format("Price breach!"));

                            /* price breach! */

                            //within market open?
                            if (percentageTimeSinceMarketOpen > 0 && percentageTimeSinceMarketOpen < 100)
                            {
                                //get par volume for this time of day
                                var parVolume = (percentageTimeSinceMarketOpen / 100) * averageVolume;

                                //get relative volume change
                                var relativeVolume = ((volume - parVolume) / parVolume) * 100;                                
                                
                                sb.AppendLine(string.Format("{0} has breached price of {1} (last trade: {2}) with {3}% relative volume. {4}",
                                    priceBreachContender.Symbol, priceBreachContender.Price, price, relativeVolume, priceBreachContender.Notes));                                                                
                            }
                        }
                        else
                        {
                            Console.WriteLine(string.Format("No breach"));
                        }
                    }
                }

                if (sb.Length > 0)
                {
                    //email result
                    var client = new SmtpClient("smtp.gmail.com", 587) { EnableSsl = true };
                    var from = new MailAddress("ssattin@gmail.com", "Simon Sattin");
                    var message = new MailMessage(from, from)
                    {
                        Subject = "Price breach update"
                    };
                    var myCreds = new NetworkCredential("ssattin@gmail.com", "bergkamp_10", "");
                    client.Credentials = myCreds;

                    message.Body = sb.ToString();

                    client.Send(message);
                }
            }
        }
    }
}
